<template>
  <div class="expense">
    <!-- Breadcrumb 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 25px">
      <el-breadcrumb-item>医院后台</el-breadcrumb-item>
      <el-breadcrumb-item>药品管理</el-breadcrumb-item>
      <el-breadcrumb-item>药品费用</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片内容 -->
    <!-- 侧边栏容器 -- 病房信息 -->
    <el-card shadow="never" border="false" :body-style="{ padding: '10px 15px !important' }" style="width: 40%; float: left">
      <el-button type="primary" @click="addExpense">添加</el-button>
      <!----- 费用筛选 - 内容 ------>
      <template>
        <el-table :data="allList" style="width: 100%; cursor: pointer; margin-top: 0" height="70vh" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
          <el-table-column prop="medicineID" label="药品ID" align="center"></el-table-column>
          <el-table-column prop="buyprice" label="进货价" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="{ row }">
              <div class="actions">
                <!-- 修改信息 -->
                <i class="el-icon-edit-outline" @click="editMedicine(row)"></i>
                <!-- 删除信息 -->
                <i class="el-icon-delete" @click="deleteMedicine(row)" style="margin-left:10px"></i>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>

    <!-- 主要区域容器 -- 病房信息 -->
    <el-card style="width: 59%; float: right">
      <template>
        <i>￥支出（{{ cost }}.00元）</i>
        <el-divider></el-divider>
        <el-table :data="multipleSelection" style="width: 100%; cursor: pointer; margin-top: 0" height="43vh" @selection-change="handleSelectionChange">
          <el-table-column prop="id" label="订单编号" align="center" width="80"></el-table-column>
          <el-table-column prop="medicineID" label="药品ID" align="center"></el-table-column>
          <el-table-column prop="medicine.name" label="药品名称" align="center" width="110"></el-table-column>
          <el-table-column prop="medicine.type" label="药品类型" align="center"></el-table-column>
          <el-table-column prop="medicine.count" label="数量" align="center" width="50"></el-table-column>
          <el-table-column prop="medicine.price" label="售价" align="center" width="50"></el-table-column>
          <el-table-column prop="buyprice" label="进货价" align="center" width="60"></el-table-column>
        </el-table>
        <el-divider></el-divider>
        <!-- 合计 -->
        <template>
          <h3 style="float: right; margin: 0 0 15px">合计：￥{{ cost }}</h3>
        </template>
      </template>
    </el-card>
    <!-- dialog--弹出框，填写|修改 订单信息 -->
    <el-dialog :title="flag == 1 ? '添加订单信息' : '修改订单信息'" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="药品ID" prop="medicineID">
          <el-input v-model="form.medicineID"></el-input>
        </el-form-item>
        <el-form-item label="药品名称" prop="medicine.name">
          <el-input v-model="form.medicine.name"> </el-input>
        </el-form-item>
        <el-form-item label="药品类型" prop="medicine.type">
          <el-input v-model="form.medicine.type"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="medicine.count">
          <el-input v-model.number="form.medicine.count"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="medicine.price">
          <el-input v-model.number="form.medicine.price"></el-input>
        </el-form-item>
        <el-form-item label="进货价" prop="buyprice">
          <el-input v-model.number="form.buyprice"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="addAdoptionInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';

export default {
  name: 'expense',
  data() {
    return {
      newDate: [],
      multipleSelection: [],
      flag: '', //标识是添加还是修改
      dialogFormVisible: false, //弹出框
      form: {
        buyprice: undefined,
        medicine: {
          count: undefined,
          name: '',
          type: '',
          price: undefined,
          medicineID: '',
        },
        medicineID: '',
      },
      //表单验证
      rules: {
        medicineID: [
          { required: true, message: '药品ID不能为空', trigger: 'blur' },
          { pattern: /^YCP-\d{4}$/, message: '格式：YCP-XXXX', trigger: 'blur' },
        ],
        buyprice: [{ type: 'number', message: '进货价只能为整型', trigger: 'blur' }],
        medicine: {
          name: [{ required: true, message: '药品名称不能为空', trigger: 'blur' }],
          type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
          price: [{ type: 'number', message: '售价只能为整型', trigger: 'blur' }],
          count: [{ type: 'number', message: '数量只能为整型', trigger: 'blur' }],
        },
      },
    };
  },

  mounted() {
    //获取所有采购信息
    this.$store.dispatch('getAllExpense');
  },

  computed: {
    ...mapState({ expenseList: state => state.expense.expenseList || [], medicineList: state => state.expense.medicineList || [] }),
    allList() {
      //删除medicineList中的id
      this.medicineList.forEach(item => {
        delete item.id;
      });
      //合并采购信息与药品信息
      return this.expenseList.map(item => {
        return {
          ...item,
          medicine: this.medicineList.find(medicine => medicine.medicineID === item.medicineID),
        };
      });
    },
    // 计算总价
    cost() {
      return this.multipleSelection.reduce((acc, cur) => {
        return acc + cur.buyprice * cur.medicine.count;
      }, 0);
    },
  },

  methods: {
    //勾选框
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //添加订单按钮
    addExpense() {
      this.flag = 1;
      this.dialogFormVisible = true;
    },
    //编辑订单信息
    editMedicine(row) {
      this.flag = 2;
      this.dialogFormVisible = true;
      //浅拷贝
      this.form = Object.assign({}, row);
    },
    //删除订单信息
    deleteMedicine(row) {
      this.$confirm('此操作将永久删除该药品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(
          //删除订单信息
          this.$store.dispatch('deleteExpenseInfo', row.id)
        )
        .then(res => {
          if (this.medicineList.length == 1) {
            //如果当前页没有数据了，就往前跳一页
            this.params.pageStart = this.params.pageStart - 1;
          }
          //重新获取订单信息
          this.$store.dispatch('getAllExpense');
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    //取消提交
    cancelAdd() {
      //清空表单
      Object.assign(this._data.form, this.$options.data().form);
      this.dialogFormVisible = false;
    },
    //提交表单
    addAdoptionInfo() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.form.medicine.medicineID = this.form.medicineID;
          //发送请求，添加订单数据
          this.$store
            .dispatch('addExpenseInfo', this.form)
            .then(res => {
              this.$store.dispatch('getAllExpense');
              if (this.flag == 1)
                //提示添加成功
                this.$message({
                  message: '添加订单成功',
                  type: 'success',
                });
              else
                this.$message({
                  message: '修改订单信息成功',
                  type: 'success',
                });
              //清空表单
              Object.assign(this._data.form, this.$options.data().form);
              //关闭添加药品对话框
              this.dialogFormVisible = false;
            })
            .then(res => {
              //重新获取数据
              Object.assign(this.expenseList, this.$store.state.expense.expenseList);
              Object.assign(this.medicineList, this.$store.state.expense.medicineList);
            });
        }
      });
    },
  },
  watch: {
    expenseList() {
      //删除medicineList中的id
      this.medicineList.forEach(item => {
        delete item.id;
      });
      //合并采购信息与药品信息
      const list = this.expenseList.map(item => {
        return {
          ...item,
          medicine: this.medicineList.find(medicine => medicine.medicineID === item.medicineID),
        };
      });
      Object.assign(this.expenseList, list);
    },
  },
};
</script>

<style lang="less" scoped>
.expense {
  //布局
  .el-col {
    font-size: 14px;
  }
}
</style>